package com.zwr.pattern.twophase;


public class TwoPhaseDemo {
    //    public static void main(String[] args) throws InterruptedException {
//        TPIntercept tpIntercept = new TPIntercept();
//        tpIntercept.start();
//        Thread.sleep(10000);
//        tpIntercept.stop();
//    }
    public static void main(String[] args) {

    }
}


/**
 * 利用停止标记
 * interrupt 可以打断正在执行的线程，无论这个线程是在 sleep，wait，还是正常运行
 */
class TPIntercept {
    private Thread thread;

    public void stop() {
        thread.interrupt();
    }

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                Thread currentThread = Thread.currentThread();
                if (currentThread.isInterrupted()) {
                    System.out.println("执行后续操作,优雅停止");
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    currentThread.interrupt();
                    e.printStackTrace();
                }
                System.out.println("记录xxxx");
            }
        });
        thread.start();
    }
}

/**
 * 利用停止标记
 */
class TPVolatile {
    private Thread thread;
    private volatile boolean stop = false;

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (stop) {
                    System.out.println("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("记录xxxx");
            }
        });
        thread.start();
    }

    public void stop() {
        stop = true;
        thread.interrupt();
    }
}
